package com.dyh.quickdemo.rulev2;

import java.util.Objects;
import java.util.function.Function;
import java.util.function.Predicate;

/*
@Author=Joey Wheeler
@Date=2021/3/8 13:36
*/
public class BaseRule<O,V>  implements Rule<O>,DependableRule<O >{

    private Function<O,V> mapper;
    private Predicate<V> checker;
    private Predicate<O> checkerForConect;//为下面拼接用
    private String tip;

    public BaseRule(Function<O, V> mapper, Predicate<V> checker, String tip) {
        this.mapper = mapper;
        this.checker = checker;
        this.tip = tip;
        this.checkerForConect = obj->checker.test(mapper.apply(obj));
    }


    @Override
    public boolean check(O obj) {
        return checkerForConect.test(obj);
    }

    @Override
    public CheckResult checkDetail(O obj) {
        return checkerForConect.test(obj)
                ?new CheckResult(true,"")
                :new CheckResult(false,tip)
                ;
    }


//    @Override
//    public Rule<O> depend(Rule<O> rule) {
//        _requireNonNullUnit();
//        Predicate<V> that = this.checker;
//        that = v -> {
//            rule.check()
//        };
//    }

    private void _requireNonNullUnit(){
        Objects.requireNonNull(mapper);
        Objects.requireNonNull(checker);
    }


    @Override
    public Rule<O> depend(Rule<O> rule) {
        Predicate<O> that = this.checkerForConect;
        this.checkerForConect = obj->
                !rule.check(obj)||that.test(obj);
        return this;
    }
}
